package cn.wildfire.chat.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.classes.ResponseEntity;
import cn.wildfire.chat.app.extendsion.classes.ResponsePhoneNumberUserInfo;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.remote.ChatManager;

/**
 * @author Lizhong
 * <p>
 * TODO 忘记密码前输入手机号码验证
 */
public class ForgetPasswordInputPhoneActivity extends WfcBaseActivity {

    @BindView(R2.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R2.id.selectedCountryTxt)
    TextView selectedCountryTxt;
    @BindView(R2.id.authCodeEditText)
    EditText authCodeEditText;
    @BindView(R2.id.iv_auth_code)
    ImageView ivAuthCode;

    /**
     * 当前选中的国家区号
     */
    private Region currentRegion;

    @Override
    protected void afterViews() {
        super.afterViews();
        if (currentRegion == null) {
            currentRegion = new Region(438, "86", getString(R.string.default_country));
        }
        selectedCountryTxt.setText(currentRegion.regionName);
        requestAuthCode();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_forget_password_input_phone;
    }

    @OnClick({R2.id.tv_country_selector, R2.id.selectedCountryTxt, R2.id.btn_next_step, R2.id.iv_auth_code, R2.id.rl_img_auth_code})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.selectedCountryTxt || id == R.id.tv_country_selector) {
            Intent intent = new Intent(this, CountrySetActivity.class);
            intent.putExtra("RegionList", ((CaiBaChatApp) getApplicationContext()).regionFetcher.getmRegionRet());
            startActivityForResult(intent, 101);
        } else if (id == R.id.btn_next_step) {
            doNext();
        } else if (id == R.id.rl_img_auth_code || id == R.id.iv_auth_code) {
            try {
                if (ChatManager.Instance().getClientId() != null) {
                    requestAuthCode();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void doNext() {
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        if (TextUtils.isTextEmpty(phoneNumber)) {
            ToastTip.tip(getString(R.string.phone_is_not_null));
            return;
        }
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber parseNumber = phoneNumberUtil.parse("+" + currentRegion.regionCode + phoneNumber, currentRegion.regionCode);
            boolean validNumber = phoneNumberUtil.isValidNumber(parseNumber);
            if (!validNumber) {
                ToastTip.tip(getString(R.string.phone_number_illegal));
                return;
            }
        } catch (NumberParseException e) {
            e.printStackTrace();
        }

        String authCodeText = authCodeEditText.getText().toString().trim();
        if(TextUtils.isTextEmpty(authCodeText)){
            ToastTip.tip(getString(R.string.verification_can_not_empty));
            return;
        }

        HashMap<String, Object> params = new HashMap<>();
        try {
            params.put("mobile", phoneNumber);
            params.put("regionId", currentRegion.id);
            params.put("cid", ChatManager.Instance().getClientId());
            params.put("code", authCodeText);
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpRequest.getInstance(this).requestAsynJsonObject(ServerUrlClient.GET_USER_INFO_BY_PHONE_NUMBER, params, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                ResponseEntity<JsonObject, String> responseEntity = new ResponseEntity(result.toString());
                if (!responseEntity.getErrorCode().equals("0")) {
                    ToastTip.tip(responseEntity.message);
                    return;
                }

                if (!TextUtils.isTextEmpty(result.toString())) {
                    try {
                        Gson gson = new Gson();
                        ResponsePhoneNumberUserInfo responsePhoneNumberUserInfo = gson.fromJson(result.toString(), ResponsePhoneNumberUserInfo.class);
                        Intent intentForgetPassword = new Intent(ForgetPasswordInputPhoneActivity.this, ForgetPasswordActivity.class);
                        intentForgetPassword.putExtra("UserInfo", responsePhoneNumberUserInfo);
                        intentForgetPassword.putExtra("CountryName", currentRegion.regionName);
                        startActivity(intentForgetPassword);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        }).request();


    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setReplaceTitle(null, R.string.input_phone_number);
        setSearchLayoutVisibility(false);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调选择国家编码
        try {
            if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
                currentRegion = data.getParcelableExtra("mRegion");
                if (currentRegion != null) {
                    selectedCountryTxt.setText(currentRegion.regionName);
                } else {
                    currentRegion = new Region(438, "86", getString(R.string.default_country));
                    selectedCountryTxt.setText(currentRegion.regionName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void requestAuthCode() {
        try {
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            Glide.with(ForgetPasswordInputPhoneActivity.this).load(ServerUrlClient.GET_RANDOM_VIFCODE + "?cid=" + ChatManager.Instance().getClientId())
                    .apply(requestOptions).into(ivAuthCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
